<template>
    <div class="role-container auto-height-container">
        <vab-query-form>
            <vab-query-form-left-panel :span="8">
                <el-button v-permissions="{
                    permission: ['system:role:doAdd']
                }" type="primary" @click="handleAdd" :icon="Plus">新增</el-button>
            </vab-query-form-left-panel>
            <vab-query-form-right-panel :span="16">
                <el-form :inline="true" :model="queryForm">
                    <el-form-item style="margin-right: 10px !important;">
                        <el-input v-model="queryForm.name" placeholder="请输入角色名称" clearable @keyup.enter="fetchData" />
                    </el-form-item>
                    <el-form-item style="margin-right: 10px !important;">
                        <el-select v-model="queryForm.status" placeholder="请选择状态" clearable filterable>
                            <el-option label="正常" :value="1" />
                            <el-option label="禁用" :value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="fetchData">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </vab-query-form-right-panel>
        </vab-query-form>

        <el-table v-loading="loading" :data="list" border height="100%">
            <el-table-column prop="role_id" label="ID" width="80" align="center" show-overflow-tooltip />
            <el-table-column prop="name" label="角色名称" min-width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="code" label="角色编码" min-width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="remark" label="备注" min-width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="80" align="center">
                <template #default="{ row }">
                    <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                        {{ row.status === 1 ? '正常' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" min-width="160" align="center" show-overflow-tooltip />
            <el-table-column prop="update_time" label="更新时间" min-width="160" align="center" show-overflow-tooltip />
            <el-table-column label="操作" width="200" align="center" fixed="right">
                <template #default="{ row }">
                    <el-button 
                        v-permissions="{
                            permission: ['system:role:doEdit']
                        }" 
                        type="primary" 
                        link 
                        @click="handleEdit(row)"
                        :disabled="row.code === 'super_admin'"
                    >编辑</el-button>
                    <el-button 
                        v-permissions="{
                            permission: ['system:role:doDelete']
                        }" 
                        type="danger" 
                        link 
                        @click="handleDelete(row)"
                        :disabled="row.code === 'super_admin'"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <vab-pagination
            v-model:current-page="queryForm.pageNo"
            v-model:page-size="queryForm.pageSize"
            :total="total"
            @current-change="fetchData"
            @size-change="fetchData"
        />

        <role-form-edit
            v-model:visible="dialogVisible"
            :type="dialogType"
            :current-row="currentRow"
            @success="fetchData"
        />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getRoleList, deleteRole } from '/@/api/role'
import type { RoleForm } from '/@/api/role'
import RoleFormEdit from './components/RoleForm.vue'

const loading = ref(false)
const list = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentRow = ref<RoleForm | null>(null)

const queryForm = reactive({
    pageNo: 1,
    pageSize: 10,
    name: '',
    status: '',
})

// 获取角色列表
const fetchData = async () => {
    try {
        loading.value = true
        const { data } = await getRoleList(queryForm)
        list.value = data.list
        total.value = data.total
    } catch (error) {
        console.error('获取角色列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 重置查询
const resetQuery = () => {
    queryForm.name = ''
    queryForm.status = ''
    fetchData()
}

// 处理新增
const handleAdd = () => {
    dialogType.value = 'add'
    currentRow.value = null
    dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: RoleForm) => {
    // 超级管理员不允许编辑
    if (row.code === 'super_admin') {
        ElMessage.warning('超级管理员角色不能修改')
        return
    }

    dialogType.value = 'edit'
    currentRow.value = row
    dialogVisible.value = true
}

// 处理删除
const handleDelete = async (row: RoleForm) => {
    // 超级管理员不允许删除
    if (row.code === 'super_admin') {
        ElMessage.warning('超级管理员角色不能删除')
        return
    }

    try {
        await ElMessageBox.confirm(
            '确定要删除该角色吗？删除后将无法恢复！',
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        await deleteRole(row.role_id!)
        ElMessage.success('删除成功')
        fetchData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
        }
    }
}

onMounted(() => {
    fetchData()
})
</script>

<style lang="scss" scoped>
:deep(.el-button.is-disabled) {
    // 自定义禁用状态的样式
    opacity: 0.6;
    cursor: not-allowed;
}
</style>